<?php


namespace Trawind\Skeleton\Generators;


use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Trawind\Tenancy\Traits\TenantTool;

class RequestGenerator extends Generator
{

    use TenantTool;

    protected $stub = 'controller/request';


    public function getReplacements()
    {
        return array_merge(parent::getReplacements(), [
            'table_field' => $this->getTableField(),
        ]);
    }


    /**
     * Get root namespace.
     *
     * @return string
     */
    public function getRootNamespace()
    {
        $controllerPath = str_replace('/', '\\',
            parent::getRootNamespace().parent::getConfigGeneratorClassPath($this->getPathConfigNode()));
        return str_replace('Controllers', 'Requests', $controllerPath);;
    }

    public function getTableField()
    {
        return $this->runTenantOrCentral(function () {
            $tables = Schema::getColumnListing($this->getTableName());

            $columnStr = '';
            $excludeMap = ['id', 'created_at', 'updated_at'];

            foreach ($tables as $column) {
                $tabPlaceholder = empty($columnStr) ? '' : '            ';
                if (!in_array($column, $excludeMap)) {
                    $columnStr .= $tabPlaceholder."'$column' => 'required',".PHP_EOL;
                }
            }
            return $columnStr;
        });;
    }


    public function getTableName()
    {
        $tableName = str_replace('/', '_',
            strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $this->getRealName())));
        return Str::plural($tableName);
    }


    public function getRealName()
    {
        return substr($this->getName(), 0, strlen('CreateRequest') * -1);
    }


    /**
     * Get generator path config node.
     *
     * @return string
     */
    public function getPathConfigNode()
    {
        return 'controllers';
    }

    /**
     * Get destination path for generated file.
     *
     * @return string
     */
    public function getPath()
    {
        $controllerPath = parent::getConfigGeneratorClassPath($this->getPathConfigNode(),
                true).'/'.$this->getName().'.php';
        $RequestPath = str_replace('Controllers', 'Requests', $controllerPath);
        return $this->getBasePath().'/app/'.$RequestPath;
    }
}